package gui.actions;

import javax.swing.JComponent;
import javax.swing.JOptionPane;

import common.Fictionator;
import common.interfaces.ConfigurationsInterface;

public class ResetAction extends WorkerAction {

    private static final long serialVersionUID = 1L;

    private int guiSessionID;
    private boolean closeResourcesAfterReset = false;
    
    public ResetAction(JComponent owner, int guiSessionID) {
        super(owner);
        this.guiSessionID = guiSessionID;
    }
    
    
    public ResetAction() {
        this(null, -1);
        closeResourcesAfterReset = true;
    }

    @Override
    public boolean isAllowToRunOperation() {
        // TODO DAN better messages
        String message = null;
        message = "Are you sure you want to delete all ongoing user sessions?";
        int selection = JOptionPane.showConfirmDialog(getOwner(), message, "", JOptionPane.YES_NO_OPTION);
        return selection == JOptionPane.YES_OPTION;        
    }
    
    @Override
    public void runOperation() throws Exception {
        ConfigurationsInterface config = Fictionator.getInstance().getConfigurationsLogic();
        config.forceGuiSessionCleanup(guiSessionID);
    }
    
    @Override
    public void operationSucceed() {
        if (closeResourcesAfterReset) {
            try {
                Fictionator.getInstance().getConfigurationsLogic().closeResources();
            } catch (Exception e) { /* do nothing */ }
        }
    }
    
    @Override
    public void operationFailed(Exception e) {
        if (closeResourcesAfterReset) {
            try {
                Fictionator.getInstance().getConfigurationsLogic().closeResources();
            } catch (Exception e1) { /* do nothing */ }
        }
    }
    
    public void run() {
        actionPerformed(null);
    }
    
}
